//
//  DXTextView.swift
//  weiBoOfSwift
//
//  Created by simon on 15/12/14.
//  Copyright © 2015年 simon. All rights reserved.
//

import UIKit

@IBDesignable class DXTextView: UITextView {
  
//    外界设置的占位文字
   @IBInspectable var placeHoldText:String?{
        didSet{
        placeHolder.text = placeHoldText
            
        }
    
    }
//  判断textView中是否有富文本或文本
    var hasContentText:Bool{
        
    return  (hasText() || (attributedText.string as NSString).length != 0)
    
    }
    
    override var font:UIFont?{
    
        didSet{
           placeHolder.font = font
        }
    
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewVauleDidChange:", name: UITextViewTextDidChangeNotification, object:nil)
        setUpUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
         setUpUI()
    }
//    MARK:初始化UI控件
    private func setUpUI(){
//        backgroundColor = UIColor.orangeColor()
      alwaysBounceVertical = true
        
      addSubview(placeHolder)
      

//        添加约束
        placeHolder.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeHolder, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 7))
        addConstraint(NSLayoutConstraint(item: placeHolder, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 4))
        addConstraint(NSLayoutConstraint(item: placeHolder, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Width , multiplier: 1, constant: -4))
        
        
    
    }

    // MARK: - 监听通知方法的实现
  @objc private func textViewVauleDidChange(notify:NSNotification){
    
        placeHolder.hidden = hasContentText
   
    }
    // MARK: - 懒加载
//    占位文字
    lazy var placeHolder:UILabel = {
    let placeHolder = UILabel()
//        placeHolder.backgroundColor = UIColor.redColor()
        placeHolder.numberOfLines = 0
//        placeHolder.font = UIFont.systemFontOfSize(12)
        placeHolder.textColor = UIColor.lightGrayColor()
        placeHolder.text = "占位文字"
        return placeHolder
    
    }()

//MARK:注销观察者
    deinit{
    NSNotificationCenter.defaultCenter().removeObserver(self)
    
    }
}
